<?php

namespace App\Http\Controllers\Admin;

use App\Models\Goods;
use App\Exceptions\ApiErrorException;
use App\Requests\Admin\MarketActivity\MarketActivitySaveRequest;
use App\Models\MarketActivityMaterialModel;
use App\Models\MarketActivityModel;
use App\Services\CommonService;
use App\Traits\CurdTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;

class MarketActivityController extends BaseController
{
    use CurdTrait;

    /**
     * @var MarketActivityModel
     */
    protected $curdModel;

    public function _init()
    {
        parent::_init();
        $this->setCurdModel(new MarketActivityModel());
    }

    /**
     * 列表
     * @param \Illuminate\Http\Request $request
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/16
     */
    public function list(Request $request)
    {
        $paramsId = $request->input('id');
        $paramsName = $request->input('name');
        $paramsStatus = $request->input('status');

        $paginate = $this->curdModel
            ->when($paramsId, function($q) use ($paramsId) {
                $q->where('id', $paramsId);
            })
            ->when($paramsName, function($q) use ($paramsName) {
                $q->where('name', 'like', '%' . $paramsName . '%');
            })
            ->when($paramsStatus, function($q) use ($paramsStatus) {
                $q->where('status', $paramsStatus);
            })
            ->when($request->input('begin_time'), function($q) use ($request) {
                $q->where('begin_time', '>=', $request->input('begin_time'));
            })
            ->when($request->input('end_time'), function($q) use ($request) {
                $q->where('end_time', '<=', $request->input('end_time'));
            })
            ->when($request->input('create_by_id'), function($q) use ($request) {
                $q->where('create_by_id', '=', $request->input('create_by_id'));
            })
            ->select('id', 'create_time', 'uid', 'name', 'status', 'begin_time', 'end_time', 'cover_img', 'create_by_id', 'create_by')
            ->paginate($this->pageSize);

        return $this->responseSuccess('', [
            'list' => $paginate->items(),
            'total' => $paginate->total(),
        ]);
    }

    /**
     * 详情
     * @param \Illuminate\Http\Request $request
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    public function info(Request $request)
    {
        $id = $request->input('id');
        $model = $this->curdModel->find($id);
        if (empty($model)) {
            return $this->responseFail('数据不存在');
        }

        return $this->responseSuccess('', $model);
    }

    /**
     * 保存
     * @param \Illuminate\Foundation\Http\FormRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    public function save(MarketActivitySaveRequest $request)
    {
        $id = $request->input('id');
        if ($id) {
            return $this->edit($request);
        }
        else {
            return $this->add($request);
        }
    }

    /**
     * 添加
     * @param \Illuminate\Foundation\Http\FormRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @author Chris Yu <chrisyu@crabapple.top> 2024/12/18
     */
    protected function add(MarketActivitySaveRequest $request)
    {
        $saveData = $request->validationData();
        $saveData['uid'] = str_replace('-', '', Uuid::uuid4()->toString());

        DB::beginTransaction();

        $row = $this->curdModel->create($saveData);
        if (!$row) {
            return $this->responseFail('添加失败');
        }

        DB::commit();

        return $this->responseSuccess('添加成功', ['id' => $row->getKey()]);
    }

    /**
     * 编辑
     * @param \Illuminate\Foundation\Http\FormRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    protected function edit(MarketActivitySaveRequest $request)
    {
        $id = $request->input('id');

        $row = $this->curdModel->find($id);
        if (empty($row)) {
            return $this->responseFail('数据不存在');
        }

        $saveData = $request->validated();
        unset($saveData['id']);

        DB::beginTransaction();

        $res = $row->fill($saveData)->save();
        if (!$res) {
            return $this->responseFail('编辑失败');
        }

        DB::commit();

        return $this->responseSuccess('编辑成功', ['id' => $row->getKey()]);
    }

    /**
     * 删除
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    public function delete(Request $request)
    {
        $id = $request->input('id');

        $row = $this->curdModel->find($id);
        if (empty($row)) {
            return $this->responseFail('数据不存在');
        }

        DB::beginTransaction();

        $res = $row->delete();
        if (!$res) {
            return $this->responseFail('删除失败');
        }

        DB::commit();

        return $this->responseSuccess('删除成功');
    }

    /**
     * 预览
     * @param \Illuminate\Http\Request $request
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    public function switchStatus(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status');
        $row = $this->curdModel->find($id);
        if (empty($row)) {
            return $this->responseFail('数据不存在');
        }

        $row->update([
            'status' => $status,
        ]);

        return $this->responseSuccess();
    }

    /**
     * 获取商品详情，用于活动详情页
     */
    public function goodsInfo(Request $request)
    {
        $id = $request->input('goods_id');

        $cacheKey = "market_activity:goods_info:{$id}";
        if (config('app.cache_enable') && Cache::has($cacheKey)) {
            $goods = Cache::get($cacheKey);
            return $this->responseSuccess('', $goods);
        }

        $goods = Goods::query()
            ->whereKey($id)
            ->select('id', 'title', 'imgurl', 'min_price')
            ->first();
        if (empty($goods)) {
            return $this->responseFail('商品不存在');
        }

        Cache::put($cacheKey, $goods, 60 * 60);
        return $this->responseSuccess('', $goods);
    }

    /**
     * 素材列表
     * @param \Illuminate\Http\Request $request
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/9
     */
    public function materialList(Request $request)
    {
        $material_list = MarketActivityMaterialModel::where([
            'is_delete' => CommonService::IS_DELETE_NOT,
        ])->get();

        return $this->responseSuccess('', $material_list);
    }

    /**
     * 保存素材
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiErrorException
     */
    public function materialAdd(Request $request)
    {
        $this->checkParams($request->all(), ['title', 'config_json']);

        $title = strval($request->input('title'));
        $config_json = strval($request->input('config_json'));

        $mkt_activity_m = new MarketActivityMaterialModel();

        $mkt_activity_m->title = $title;
        $mkt_activity_m->config_json = $config_json;

        $mkt_activity_m->save();

        return $this->responseSuccess('保存素材成功', [
            'id' => $mkt_activity_m->id,
        ]);
    }

    /**
     * 删除素材
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function materialDelete(Request $request)
    {
        $id = $request->input('id');

        $update_data = [
            'is_delete' => CommonService::IS_DELETE_YES,
        ];

        MarketActivityMaterialModel::where(['id' => $id])->update($update_data);

        return $this->responseSuccess('删除成功');
    }
}
